package com.chookss.mine.personal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.chookss.WebCommonActivity;
import com.chookss.tools.NavigationTools;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.mine.MyOrderPagerAdapter;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.old.SignUtils;
import com.chookss.view.CircleImageView;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.chookss.view.consecutivescroller.ConsecutiveViewPager;
import com.chookss.view.consecutivescroller.TabPagerAdapter;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PersonalHomeActivity extends BaseAct {

    @BindView(R.id.llBack)
    LinearLayout llBack;
    @BindView(R.id.ll_mine_top)
    LinearLayout llMineTop;
    @BindView(R.id.llFocus)
    LinearLayout llFocus;
    @BindView(R.id.tvFocus)
    TextView tvFocus;
    @BindView(R.id.tvAbility)
    TextView tvAbility;
    @BindView(R.id.ivUserImg)
    CircleImageView ivUserImg;
    @BindView(R.id.tvUserName)
    TextView tvUserName;
    @BindView(R.id.tvAge)
    TextView tvAge;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.tvJob)
    TextView tvJob;
    @BindView(R.id.llThreeInfo)
    LinearLayout llThreeInfo;
    @BindView(R.id.tvPraiseNum)
    TextView tvPraiseNum;
    @BindView(R.id.tvFocusOnNum)
    TextView tvFocusOnNum;
    @BindView(R.id.tvFansNumb)
    TextView tvFansNumb;
    @BindView(R.id.tvCollectNum)
    TextView tvCollectNum;
    @BindView(R.id.llFourInfo)
    LinearLayout llFourInfo;
    @BindView(R.id.rlUserInfos)
    RelativeLayout rlUserInfos;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ConsecutiveViewPager viewPager;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.llLevel)
    LinearLayout llLevel;
    @BindView(R.id.ivLevel)
    ImageView ivLevel;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    private Context mContext;
    private String employeeCode;
    private MineInfoEntity mineInfoEntity;
    private String[] title = {"视频", "集合", "新闻", "课程"};
    private MyOrderPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private int type = 1;//0自己的主页1别人的主页
    private MyVideoFragment myVideoFragment;
    private MyVediosFragment myVediosFragment;
    private MyNewsFragment myNewsFragment;
    private MyLongVideosFragment myLongVideosFragment;

    // 提供给Fragment获取使用。
    public SmartRefreshLayout getRefreshLayout() {
        return refreshLayout;
    }

    private TabPagerAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mines);
        employeeCode = getIntent().getStringExtra("employeeCode");
        mContext = this;
        initState2();
        init();
    }

    private void init() {
        int statusBarHeight = Utils.getStatusBarHeight(mContext);
        RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) llMineTop.getLayoutParams();
        topAllParams.setMargins(0, statusBarHeight, 0, 0);
        llMineTop.setLayoutParams(topAllParams);
        String localEmployeeCode = new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
        if (localEmployeeCode.equals(localEmployeeCode)) {
            type = 0;
        } else {
            type = 1;
        }
        myVideoFragment = new MyVideoFragment(employeeCode, type);
        myVediosFragment = new MyVediosFragment(employeeCode, type);
        myNewsFragment = new MyNewsFragment(employeeCode, type);
        myLongVideosFragment = new MyLongVideosFragment(employeeCode, type);
        fragments.add(myVideoFragment);
        fragments.add(myVediosFragment);
        fragments.add(myNewsFragment);
        fragments.add(myLongVideosFragment);
        mAdapter = new TabPagerAdapter(getSupportFragmentManager(), getTabs(), fragments);
        viewPager.setAdapter(mAdapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                viewPager.setAdjustHeight(tabLayout.getHeight());
            }
        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout r) {
                // 把加载的动作传给当初的fragment
                if (viewPager.getCurrentItem() == 0) {
                    myVideoFragment.onLoadMore(refreshLayout);
                } else if (viewPager.getCurrentItem() == 1) {
                    myVediosFragment.onLoadMore(refreshLayout);
                } else if (viewPager.getCurrentItem() == 2) {
                    myNewsFragment.onLoadMore(refreshLayout);
                } else {
                    myLongVideosFragment.onLoadMore(refreshLayout);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout r) {
                if (viewPager.getCurrentItem() == 0) {
                    myVideoFragment.onRefresh(refreshLayout);
                } else if (viewPager.getCurrentItem() == 1) {
                    myVediosFragment.onRefresh(refreshLayout);
                } else if (viewPager.getCurrentItem() == 2) {
                    myNewsFragment.onLoadMore(refreshLayout);
                } else {
                    myLongVideosFragment.onLoadMore(refreshLayout);
                }
            }
        });
        llBack.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        getData();
    }

    private void getData() {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", employeeCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.getMyInfo, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                mineInfoEntity = data;
                if(tvUserName==null){
                    return;
                }
                tvUserName.setText(mineInfoEntity.getNickName());
                tvJob.setText(mineInfoEntity.getPost());
                tvAge.setText(mineInfoEntity.getAge() + "岁");
                tvLocation.setText(mineInfoEntity.getAddress().replace("、","·"));
                tvFansNumb.setText(mineInfoEntity.getFansNum());
                tvFocusOnNum.setText(mineInfoEntity.getFocusOnNum());
                tvPraiseNum.setText(mineInfoEntity.getGetPraiseNum());
                tvCollectNum.setText(mineInfoEntity.getCollectNum());
                tvLevel.setText(data.getLvlName());
                if (!Utils.isNull(data.getLvlImage())) {
                    String url = data.getLvlImage();
                    GlideUtils.load(mContext, url, ivLevel, R.drawable.icon_wangzhe_23);
                }
                if (mineInfoEntity.getEmployeeCode().equals(new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, ""))) {
                    //本人
                    llFocus.setVisibility(View.GONE);
                } else {
                    llFocus.setVisibility(View.VISIBLE);
                    if ("1".equals(mineInfoEntity.getIsFans())) {
                        tvFocus.setText("已关注");
                    }
                }
                GlideUtils.loadAvatar(mContext, mineInfoEntity.getHeadPhotoUrl(), ivUserImg);
                dismissLoading();
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void toFollow() {
        Map<String, String> allmap = new HashMap<>();
        String followStatus = "1";
        if (!"关注".equals(tvFocus.getText().toString())) {
            followStatus = "0";
        }
        allmap.put("employeeCode", employeeCode);
        allmap.put("followStatus", followStatus);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.toFollow, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if(tvFocus==null){
                    return;
                }
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject result_object = reObject.getJSONObject("data");
                    if ("true".equals(result_object.getString("rst"))) {
                        if ("关注".equals(tvFocus.getText().toString())) {
                            MyToast.show("关注成功");
                            tvFocus.setText("已关注");
                        } else {
                            MyToast.show("取消关注");
                            tvFocus.setText("关注");
                        }
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }


    @OnClick({R.id.llBack, R.id.tvFocus, R.id.tvAbility, R.id.llLevel})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.llBack:
                finish();
                break;
            case R.id.llLevel:
                intent = new Intent(mContext, WebCommonActivity.class);
                intent.putExtra("url", NavigationTools.getAllUrl(mContext, Urls.getCapacityAnalysisGrowth) + "&employeeCode=" +employeeCode);
                intent.putExtra("title", "段位");
                mContext.startActivity(intent);
                break;
            case R.id.tvFocus:
                if (Urls.antiShake.check()) {
                    return;
                }
                toFollow();
                break;
            case R.id.tvAbility:
                if (Urls.antiShake.check()) {
                    return;
                }
                intent = new Intent(mContext, WebCommonActivity.class);
                String abilityUrl = NavigationTools.getAllUrl2(mContext, Urls.getCapacityAnalysisCapacity) + "&employeeCode=" + employeeCode;
                if (abilityUrl != null) {
                    intent.putExtra("url", abilityUrl);
                    intent.putExtra("userName", tvUserName.getText().toString());
                    intent.putExtra("isPersonalAbility", true);
                    intent.putExtra("title", tvUserName.getText().toString()+"的能力分析");
                    mContext.startActivity(intent);
                }
                break;
        }

    }

    private List<String> getTabs() {
        List<String> tabs = new ArrayList<>();
        tabs.add("视频");
        tabs.add("集合");
        tabs.add("新闻");
        tabs.add("课程");
        return tabs;
    }

}
